package cn.itcast.hotel;


import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Stats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.CollectionUtils;
import org.springframework.boot.test.context.SpringBootTest;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.security.PublicKey;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class EsSerachDemo {


    @Test
    public  void aggregations2() throws IOException {

        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.size(0);

        source.aggregation(
                AggregationBuilders.stats("statsAgg")
                        .field("price")

        );

        SearchResponse response = client.search(request,RequestOptions.DEFAULT);

        Aggregations aggregations = response.getAggregations();

        Stats statsRsult = aggregations.get("statsAgg");
        System.out.println(statsRsult.getAvg());


    }


    @Test
    public  void aggregations() throws IOException {

        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.size(0);

        source.aggregation(
                AggregationBuilders.terms("brandAgg")
                .field("brand")
                .size(20)
        );

        SearchResponse response = client.search(request,RequestOptions.DEFAULT);

        Aggregations aggregations = response.getAggregations();

        Terms termsRsult = aggregations.get("brandAgg");

        List<? extends Terms.Bucket> buckets = termsRsult.getBuckets();

        for (Terms.Bucket bucket : buckets) {

            System.out.println("分组key值" +  bucket.getKeyAsString());
            System.out.println("文档数量" +  bucket.getDocCount());
        }

    }





    @Test
    public void testPageAndSort() throws IOException {
        int page = 2;
        int size = 3;


        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        source.sort("score", SortOrder.DESC);
        source.sort("price",SortOrder.ASC);

        source.from((page - 1) * size);
        source.size(size);

        SearchResponse response = client.search(request,RequestOptions.DEFAULT);
        handleResponse(response);



    }


    @Test
    public void bool() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("city","杭州"));
        boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));

        request.source().query(boolQuery);
        SearchResponse response = client.search(request,RequestOptions.DEFAULT);

        handleResponse(response);



    }





    @Test
    public void testMatch() throws IOException {

        SearchRequest request = new SearchRequest("hotel");

        request.source().query(QueryBuilders.matchQuery("all", "如家"));

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        handleResponse(response);

    }

    @Test
    public void matchAll() throws IOException {

        SearchRequest request = new SearchRequest("hotel");

        SearchSourceBuilder source = request.source();

        source.query(QueryBuilders.matchAllQuery());

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        handleResponse(response);

    }
    private  void handleResponse(SearchResponse response){

        SearchHits hits = response.getHits();

        System.out.println("文档数量" + hits.getTotalHits().value);

        SearchHit[] searchHits = hits.getHits();

        for (SearchHit searchHit : searchHits) {
            String hotelJson = searchHit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(hotelJson,HotelDoc.class);

            System.out.println("hotelDoc =" + hotelDoc);
        }
    }

    RestHighLevelClient client;
    @BeforeEach
    public void init(){
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.200.130:9200")
        ));
    }

    @AfterEach
    public void close(){
        try {
            client.close();
        } catch (IOException e) {

        }
    }
}
